/**
 * 
 */
package front_shop;

import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.JTableHeader;

/**
 * @author wx
 *
 */

@SuppressWarnings("serial")
public class cashierFrame extends JFrame implements ActionListener {
	JTable cashiertable;
	JLabel shangpinbianhao,huiyuankahao,shuliang,danjia,yingshou,shishou,zhaoling,discount;
	JTextField spbh,hykh,sl,zk,ys,ss,zl;//商品编号，会员卡号，数量，单价，折扣，应收，实收，找零
	JPasswordField dj;
	JButton delete,admin,cancel,hy;//删除商品、前台转后台、交易取消
	JPanel panel;
	Connection con;
    Statement sql; 
    ResultSet rs,r;
	Object t[][]= new Object[18][8];
	int i=0;
	boolean a=false;
	public cashierFrame(){
		//创建并添加控件
		 panel=new JPanel();
		 shangpinbianhao= new JLabel("商品编号");
		 huiyuankahao= new JLabel("会员卡号");
		 shuliang= new JLabel("数量");
		 danjia= new JLabel("密码");
		 yingshou= new JLabel("应收");
		 shishou= new JLabel("实收");
		 zhaoling= new JLabel("找零");
		 discount= new JLabel("打折");
		 spbh= new JTextField(20);
		 hykh= new JTextField(20);
		 sl= new JTextField(10);
		 dj= new JPasswordField(20);
		 zk= new JTextField(10);
		 ys= new JTextField(10);
		 ss= new JTextField(10);
		 zl= new JTextField(10);
		 delete=new JButton("删除商品");
		 admin=new JButton("前台转后台");
		 cancel=new JButton("清空界面");
		 hy=new JButton("注册会员");

		 
		panel.setLayout(null);
		this.add(panel);
		panel.add(shangpinbianhao);
		shangpinbianhao.setBounds(20,330,80,20);
		panel.add(huiyuankahao);
		huiyuankahao.setBounds(20,360,80,20);
		panel.add(shuliang);
		shuliang.setBounds(200,330,40,20);
		panel.add(danjia);
		danjia.setBounds(200,360,40,20);
		panel.add(yingshou);
		yingshou.setBounds(20,390,80,40);
		panel.add(shishou);
		shishou.setBounds(230,390,80,40);
		panel.add(zhaoling);
		zhaoling.setBounds(450,390,80,40);
		panel.add(discount);
		discount.setBounds(330,330,40,20);
		panel.add(spbh);
		spbh.setBounds(80,330,100,20);
		panel.add(hykh);
		hykh.setBounds(80,360,100,20);

		panel.add(sl);
		sl.setBounds(230,330,60,20);
		panel.add(dj);
		dj.setBounds(230,360,60,20);
		panel.add(zk);
		zk.setBounds(370,330,60,20);
		panel.add(hy);
		hy.setBounds(570,330,100,20);
		panel.add(ys);
		ys.setBounds(80,390,80,40);
		panel.add(ss);
		ss.setBounds(280,390,80,40);
		panel.add(zl);
		zl.setBounds(510,390,80,40);
		panel.add(delete);
		delete.setBounds(330,360,100,20);
		panel.add(admin);
		admin.setBounds(450,360,100,20);
		panel.add(cancel);
		cancel.setBounds(570,360,100,20);

		//创建表格添加表格
		Object columnname[]={"商品编号","商品名称","规格","单位","数量","售价","折扣","金额"};
		cashiertable=new JTable(t,columnname);
		JTableHeader cashiertableheader=cashiertable.getTableHeader();
		panel.add(cashiertableheader);
		panel.add(cashiertable);
		cashiertableheader.setBounds(0,0,700,20);
		cashiertable.setBounds(0,20,680,300);

		//应收、找零、时间、单价、折扣文本框不可以修改
		ys.setEditable(false);
		zl.setEditable(false);
		zk.setEditable(false);
	
		
		admin.addActionListener(this);
		cancel.addActionListener(this);
		delete.addActionListener(this);
		hykh.addActionListener(this);
		hy.addActionListener(this);
		dj.addActionListener(this);
		spbh.addActionListener(this);
		sl.addActionListener(this);
		ss.addActionListener(this);
		
		 	try{  
			    Class.forName("com.mysql.jdbc.Driver");
			    }
		 	catch(Exception e){
			       System.out.println("忘记把MySQL数据库的JDBC-数据库驱动程序复制到JDK的扩展目录中");
			    }
		 	try { String uri= "jdbc:mysql://127.0.0.1:3306/javashop";
			          String user="root";
			          String ps="123";
			          con=DriverManager.getConnection(uri,user,ps);
			          sql=con.createStatement();
			    }
		    catch(SQLException e){ 
			          System.out.println(e);
			    }
	}
	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@SuppressWarnings("deprecation")
	public void actionPerformed(ActionEvent e){
		if (e.getSource()==delete){//删除商品按钮
			//把获得焦点的商品哪一行删除
			int q,j;
			double am;
			q=cashiertable.getSelectedRow();			
			if (q!=-1){
				for ( j=0;j<8;j++){
					t[q][j]="";
				}
			}
			for(j=q;j<i;j++){//q=2;i=3
				for (int n=0;n<8;n++){
					t[j][n]=t[j+1][n];
				}
			}
			for ( j=0;j<8;j++){
				t[i][j]="";
			}
			i--;
			cashiertable.repaint();
			double sum=0;
			 for (int J=0;J<i;J++){
				 sum=sum+Double.parseDouble(t[J][7].toString());
			 }
			 ys.setText(""+sum);
			
			
		}
		if (e.getSource()==admin){//前台转后台按钮
			administrator adminframe=new administrator();
			adminframe.setTitle("管理员登录 ");
			adminframe.setBounds(100,100,360,300);
			adminframe.setVisible(true);
			adminframe.validate();
			adminframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		}
		if (e.getSource()==cancel){//清除屏幕按钮
			//清空表格
			int i,j;
			for (i=0;i<18;i++){
				for(j=0;j<8;j++){
					t[i][j]="";
				}
			}
			cashiertable.repaint();
			hykh.setText("");
			spbh.setText("");
			sl.setText("");
			dj.setText("");
			zk.setText("");
			ys.setText("");
			ss.setText("");
			zl.setText("");
			i=0;
			a=false;
			
	
		}
		if (e.getSource()==hy){
			registered_user user=new registered_user();
			user.setTitle("注册新会员 ");
			user.setBounds(200,200,300,270);
			user.setVisible(true);
			user.validate();
			user.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		}
		if (e.getSource()==hykh){
			dj.requestFocus();
			dj.setText("");
		}
		if (e.getSource()==dj)//会员密码
		{	if (hykh.getText().equals("")){
			hykh.requestFocus();
			dj.setText("");
		}
			if (hykh.getText().length()==11&&dj.getText().length()==6){
				try{
					 rs=sql.executeQuery("SELECT * FROM usermanage where IDcard=\""+hykh.getText()+"\"");
					 if( rs.next()==true){
						 if(rs.getString(4).equals(dj.getText()))
						 { zk.setText(""+0.88);
						 	spbh.requestFocus();}
						 else 
							 {JOptionPane.showMessageDialog(this,"密码错误！！！","会员登录",JOptionPane.WARNING_MESSAGE);
							 dj.requestFocus();
							 dj.setText("");
							 }
					 }
					 else {
						 JOptionPane.showMessageDialog(this,"该用户不存在！！！","会员登录",JOptionPane.WARNING_MESSAGE);
						 hykh.requestFocus();
						 hykh.setText("");
						 dj.setText("");
					 }
				}
				  catch(SQLException a){ 
			          System.out.println(a);
			    }
			}
			else
			{ JOptionPane.showMessageDialog(this,"账号或密码格式错误！！！","会员登录",JOptionPane.WARNING_MESSAGE);
				hykh.setText("");
				dj.setText("");
				hykh.requestFocus();
			}


		}
		if (e.getSource()==spbh){
			if (spbh.getText().length()==7){ 
				try{
					 rs=sql.executeQuery("SELECT * FROM merchandise where MerchandiseNumber=\""+spbh.getText()+"\"");
					 if( rs.next()==true){//找到该商品，添加信息到收银表中
					
						 t[i][0]=rs.getString(2);
						 t[i][1]=rs.getString(5);
						// t[i][2]=rs.getString(2);
						 t[i][3]=rs.getString(7);
						// t[i][4]=rs.getString(2); shuliang
						 t[i][5]=rs.getString(6);
						 t[i][6]=zk.getText();
						// t[i][7]=rs.getString(2);jine
						 cashiertable.repaint();
						 sl.requestFocus();
						 a=true;//a true 执行过spbh

					 }
					 else //在商品表里没有找到该商品
					 { JOptionPane.showMessageDialog(this,"商品编号输入错误！！！","收银",JOptionPane.WARNING_MESSAGE);
					 spbh.requestFocus();
					 spbh.setText("");

					 }
					 
				}
				  catch(SQLException c){ 
			          System.out.println(c);
			    }
			}
			
		}
		if (e.getSource()==sl){
			double sum=0;
			if(spbh.getText().equals("")){
				spbh.requestFocus();
				sl.setText("");
				return;
			}
			if (a==false ){//在没有运行spbh的enter事件
				if (spbh.getText().length()==7){ 
					try{
						 rs=sql.executeQuery("SELECT * FROM merchandise where MerchandiseNumber=\""+spbh.getText()+"\"");
						 if( rs.next()==true){//找到该商品，添加信息到收银表中
						
							 t[i][0]=rs.getString(2);
							 t[i][1]=rs.getString(5);
							// t[i][2]=rs.getString(2);
							 t[i][3]=rs.getString(7);
							// t[i][4]=rs.getString(2); shuliang
							 t[i][5]=rs.getString(6);
							 t[i][6]=zk.getText();
							// t[i][7]=rs.getString(2);jine
							 cashiertable.repaint();
							 sl.requestFocus();
							 a=true;//

						 }
						 else //在商品表里没有找到该商品
						 { JOptionPane.showMessageDialog(this,"商品编号输入错误！！！","收银",JOptionPane.WARNING_MESSAGE);
						 spbh.requestFocus();
						 spbh.setText("");

						 }
				
					}
					  catch(SQLException a){ 
				          System.out.println(a);
				    }
				}
			}
			if (sl.getText().equals("")){
				 sl.setText("1");
			}
			if (Integer.parseInt(sl.getText())>0 ){//输入的数量大于0
				 t[i][4]=sl.getText(); 
				 if (zk.getText().equals(""))//折扣
				  t[i][7]=Double.parseDouble(sl.getText())*Double.parseDouble(t[i][5].toString());
				 else 
					 t[i][7]=Double.parseDouble(sl.getText())*Double.parseDouble(t[i][5].toString())*0.88;
				 cashiertable.repaint();
				 for (int j=0;j<=i;j++){
					 sum=sum+Double.parseDouble(t[j][7].toString());
				 }
				 String ssum = null;
				 ssum = String.format("%.2f", sum);
				 
				 ys.setText(ssum);
				 i++;
				 sl.setText("");
				 spbh.setText("");
				 spbh.requestFocus();
				 a=false;
			}
			else
				 {JOptionPane.showMessageDialog(this,"数量必须大于零！！！","收银",JOptionPane.WARNING_MESSAGE);
				 sl.setText("");
				 sl.requestFocus();
				 }

		}
		if (e.getSource()==ss){
			if (i!=0&&Double.parseDouble(ss.getText())>=Double.parseDouble(ys.getText())){
				double z=Double.parseDouble(ss.getText())-Double.parseDouble(ys.getText());
				zl.setText(""+z);
		//		JOptionPane.showMessageDialog(this,"交易成功~~","收银",JOptionPane.WARNING_MESSAGE);
				
				

				
				
				
				 String s="insert into salestatistic values";
				 Date nowTime=new Date();
				 String time=String.format("%tY-%<tm-%<td", nowTime);
				for (int j=0;j<i;j++){
					try{
						 rs=sql.executeQuery("SELECT * FROM salestatistic where MerchandiseNumber=\""+t[j][0].toString()+"\" and salesdate=\""+time+"\"");
						 if(rs.next()==true){
							 int amount=Integer.parseInt(rs.getString(3))+Integer.parseInt(t[j][4].toString());//数量
							 Double sum=amount*Double.parseDouble(rs.getString(4));//金额
							 String w="update salestatistic set amount="+amount+",salesmoney="+sum+" where MerchandiseNumber=\""+t[j][0].toString()+"\" and salesdate=\""+time+"\"";
							 int ok=sql.executeUpdate(w); 
							 
							 //更改库存
							 r=sql.executeQuery("SELECT * FROM stock where MerchandiseNumber=\""+t[j][0].toString()+"\"");
							 if(r.next()==true){
								 amount=Integer.parseInt(r.getString(3))-Integer.parseInt(t[j][4].toString());
								 w="update stock set number="+amount+" where MerchandiseNumber=\""+t[j][0].toString()+"\"";
								 ok=sql.executeUpdate(w);
								// r=sql.executeQuery("SELECT * FROM stock where MerchandiseNumber=\""+t[j][0].toString()+"\"");
							    //	 r.next();
								// System.out.println(r.getString(3));
							 }
							 else {
								 JOptionPane.showMessageDialog(this,"更新库存表失败！！！","收银",JOptionPane.WARNING_MESSAGE);
							 }
							 //更改每日收入
							 r=sql.executeQuery("SELECT * FROM cashbalance where date=\""+time+"\"");
							 double a=0.0;
							 if(r.next()==true){//更新
								 if (r.getString(2)!=null)
									 a=Double.parseDouble(r.getString(2));
								 a=a+Double.parseDouble(ys.getText());
								 w="update cashbalance set income="+a+" where date=\""+time+"\"";
								 ok=sql.executeUpdate(w);
							 }
							 else
							 {
								 a=Double.parseDouble(ys.getText());
								 w="insert into cashbalance (date,income) values ( \""+time+"\","+a+")";
								 ok=sql.executeUpdate(w);
							 }
						 }
						 else 
						 {
							 s=s+"(\""+t[j][0].toString()+"\",\""+t[j][1].toString()+"\",\""+t[j][4].toString()+"\",\""+t[j][5].toString()+"\",\""+time+"\",\""+t[j][7].toString()+"\")";
							 int ok=sql.executeUpdate(s);  
							 s="insert into salestatistic values";
						 }
						 

							
					
					}
					catch(SQLException a){
				          System.out.println(a);
					}
				}
				xp frame=new xp(t,i,hykh.getText(),ys.getText(),ss.getText(),zl.getText());
				frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
				frame.setTitle("购物小票 ");
				frame.setBounds(400,100,250,490);
				frame.setVisible(true);
				frame.validate();
				frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

				//请空表格
				
				i=0;//下次收银从表头开始输出信息
				int b,c;
				for (b=0;b<18;b++){
					for(c=0;c<8;c++){
						t[b][c]="";
					}
				}
				cashiertable.repaint();
				hykh.setText("");
				spbh.setText("");
				sl.setText("");
				dj.setText("");
				zk.setText("");
				ys.setText("");
				ss.setText("");
				zl.setText("");
				spbh.requestFocus();
				a=false;

			}
		
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		cashierFrame cashierframe=new cashierFrame();
		cashierframe.setTitle("超市前台收银系统 ");
		cashierframe.setBounds(100,100,700,500);
		cashierframe.setVisible(true);
		cashierframe.validate();
		cashierframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		}
}

